package com.zhyonk.controller;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.lang.Console;
import cn.hutool.core.util.NumberUtil;
import com.zhyonk.config.propreties.ByteDanceProperties;
import com.zhyonk.domain.AjaxResult;
import com.zhyonk.domain.StarUser;
import com.zhyonk.mapper.StarUserMapper;
import com.zhyonk.service.FaceService;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.*;

@Controller
@RequestMapping("/face")
public class FaceController {

    @Autowired
    private FaceService payService;

    @Autowired
    private StarUserMapper starUserMapper;

    @RequestMapping("/payMoney")
    @ResponseBody
//    @SentinelResource(value = "payMoney",blockHandler = "exceptionHandler",blockHandlerClass = SentinelException.class)
    public HashMap pay() {
        System.out.println("this is the request!! ");
        HashMap<String, String> map = new HashMap<>();
        map.put("result", "支付成功");
        return map;
    }

    //    @SentinelResource(value = "payFor",blockHandler = "exceptionHandler",blockHandlerClass = SentinelException.class)
    @RequestMapping(value = "/payFor",produces = { "application/json;charset=UTF-8" })
    @ResponseBody
    public void payFor(@RequestParam(value = "obj") String obj) {
        System.out.println("this is the provider! pay-model");
        payService.payFor(obj);
    }

    @RequestMapping(value = "/addUser",produces = { "application/json;charset=UTF-8" })
    @ResponseBody
    public void addUser() {
        System.out.println("this is the provider! pay-model");
//        payService.fillUser();
        payService.registerAllUserToBaidu();
//        payService.deleteFace();
    }

    @RequestMapping(value = "/searchUser",produces = { "application/json;charset=UTF-8" })
    @ResponseBody
    public Object searchUser(HttpServletRequest request) {
        MultipartFile file = ((MultipartHttpServletRequest) request).getFile("file");
        if (Objects.requireNonNull(file).isEmpty()) {
            return AjaxResult.error("请上传图片");
        }


        String encode = null;
        try {
            encode = Base64.encode(file.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
        HashMap<String, Object> result = new HashMap<>();

        ArrayList<StarUser> starList = getStarList(encode);
        if (Objects.isNull(starList)) {
            return AjaxResult.error();
        }
        result.put("starList", starList);
        return AjaxResult.success(result);
    }

    private ArrayList<StarUser> getStarList(String base64) {
        HashMap<String, String> option = new HashMap<>();
        option.put("max_user_num", "3");
        JSONObject jsonObject = payService.searchFace(option, base64, "BASE64", "star");

        if (jsonObject.getInt("error_code") != 0) {
            System.out.println(jsonObject.getString("error_msg"));
            return null;
        }
        JSONArray jsonArray = jsonObject.getJSONObject("result").getJSONArray("user_list");

        ArrayList<StarUser> starList = new ArrayList<>();

        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject item = jsonArray.getJSONObject(i);
            long userId = item.getLong("user_id");
            StarUser user = starUserMapper.selectById(userId);
            double score = item.getDouble("score");
            user.setScoure(NumberUtil.decimalFormat("0.00", score));
            starList.add(user);
        }
        return starList;
    }

    @RequestMapping(value = "/getCheckImgViolation",produces = { "application/json;charset=UTF-8" })
    @ResponseBody
    public AjaxResult getCheckImgViolation(@RequestBody HashMap<String, Object> param) {

        String base64 = param.get("base64").toString();
        if (Objects.requireNonNull(base64).isEmpty()) {
            return AjaxResult.error("请上传图片");
        }

        base64 = base64.substring(22);
        HashMap<String, Boolean> checkImageMap = ByteDanceProperties.getCheckImage(base64);
        //说明包含违规内容
        if (Objects.nonNull(checkImageMap)) {
            if (checkImageMap.size() > 0) {
                String text = getContentStr(checkImageMap);
                return AjaxResult.error("您所上传的图片涉及违规内容：" + text + "。");
            }
        }
        HashMap<String, Object> result = new HashMap<>();
        int faceCount = containFaceCount(base64);
        if (faceCount == 1) {
            //查明星列表
            ArrayList<StarUser> starList = getStarList(base64);
            result.put("result", true);
            result.put("starList", starList);
            Console.log("明星相似度测试成功 +1！！！！！！");
            return AjaxResult.success(result);
        } else if (faceCount > 1) {
            return AjaxResult.error("有超过一个的人脸数量");
        } else {
            return AjaxResult.error("未检测到人脸！");
        }
    }

    @RequestMapping(value = "/checkImage",produces = { "application/json;charset=UTF-8" })
    @ResponseBody
    public AjaxResult checkImage(@RequestBody HashMap<String, Object> param) {
        Console.log("进入查询违规的操作");
        String base64 = param.get("base64").toString();
        if (Objects.requireNonNull(base64).isEmpty()) {
            return AjaxResult.error("请上传图片");
        }

        base64 = base64.substring(22);
        HashMap<String, Boolean> checkImageMap = ByteDanceProperties.getCheckImage(base64);
//        说明包含违规内容
        if (Objects.nonNull(checkImageMap)) {
            if (checkImageMap.size() > 0) {
                String text = getContentStr(checkImageMap);
                Console.log("您所上传的图片涉及违规内容：" + text + "。");
                return AjaxResult.error("您所上传的图片涉及违规内容：" + text + "。");
            } else {
                Console.log("不违规");
                return AjaxResult.success("不违规");
            }
        }
        return AjaxResult.error("未知异常");
    }

    @RequestMapping(value = "/checkText",produces = { "application/json;charset=UTF-8" })
    @ResponseBody
    public AjaxResult checkText(@RequestBody HashMap<String, Object> param) {

        String inputText = param.get("text").toString();
        if (Objects.requireNonNull(inputText).isEmpty()) {
            return AjaxResult.error("请至少输入文字");
        }
        boolean checkTextMap = ByteDanceProperties.getCheckText(inputText);
        //说明包含违规内容
        if (checkTextMap) {
            return AjaxResult.success("不违规");
        } else {
            return AjaxResult.error("您所填写内容有敏感字段");
        }
    }

    private String getContentStr(HashMap<String, Boolean> checkImageMap) {
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, Boolean> item : checkImageMap.entrySet()) {
            String key = item.getKey();
            if ("porn".equals(key)) {
                sb.append("色情");
            } else if ("ad".equals(key)) {
                sb.append("广告");
            } else if ("politics".equals(key)) {
                sb.append("政治");
            } else if ("disgusting".equals(key)) {
                sb.append("恶心，低俗");
            }
            if (checkImageMap.size() > 1) {
                sb.append("、");
            }
        }
        if (checkImageMap.size() > 1) {
            sb.deleteCharAt(sb.length() - 1);
        }
        return sb.toString();
    }

    private int containFaceCount(String base64) {
        return payService.containFaceCount(base64);
    }
}
